package com.haredot.service.impl;

import com.haredot.entity.Btn;
import com.haredot.exception.ServiceAccessException;
import com.haredot.mapper.BtnMapper;
import com.haredot.service.BtnService;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class BtnServiceImpl implements BtnService {

    @Resource
    private BtnMapper btnMapper ;

    @Override
    public R<Btn> queryBtnsByFunc(Long funcId) {
        List<Btn> list = btnMapper.findBtnsByFuncId(funcId) ;
        return R.<Btn>ok().data(list);
    }

    @Override
    public R<?> saveBtn(Btn btn) {
        // 根据权限标记查询是否有重复
        Btn remarkBtn = btnMapper.findBtnByRemark(btn.getRemark());

        if (remarkBtn != null) return R.fail(R.StatusCode.BAD).data(Map.of("remark", "权限标记已存在"));

        int len = btnMapper.insert(btn);
        if (len != 1) throw new ServiceAccessException("插入按钮失败、期待影响 1 条、实际影响" + len + "条");
        return R.ok().build();
    }

    @Override
    public R<?> updateBtn(Btn btn) {

        // 根据权限标记查询是否有重复
        Btn remarkBtn = btnMapper.findBtnByRemark(btn.getRemark());

        if (remarkBtn != null && !Objects.equals(btn.getId(), remarkBtn.getId())) {
            return R.fail(R.StatusCode.BAD).data(Map.of("remark", "权限标记已存在"));
        }

        int len = btnMapper.update(btn);

        if (len != 1) throw new ServiceAccessException("修改按钮失败、期待影响 1 条、实际影响" + len + "条");

        return R.ok().build();
    }

    @Override
    public R<?> removeBtn(Long btnId) {

        int len = btnMapper.deleteById(btnId);

        if (len != 1) throw new ServiceAccessException("删除按钮失败、期待影响 1 条、实际影响" + len + "条");

        return R.ok().build();
    }
}
